<?php

namespace Biz\service\brandPack;

use Biz\model\brand\BrandOrder;
use Biz\model\brand\BrandOrder as mBrandOrder;
use Biz\model\brand\BrandRenewPackage;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandRights\BrandLevelRights as mBrandLevelRights;
use Biz\model\brandRights\BrandRightsAll as mBrandRightsAll;
use Biz\model\brandRights\BrandRightsRecored as mBrandRightsRecored;
use Biz\service\BrandRights\BrandLevelRightsService;
use Biz\service\BrandRights\BrandPackageRightsConfigService;
use Biz\service\BrandRights\BrandPackageService;
use Biz\service\BrandRights\BrandRightsAllService;
use Biz\service\BrandRights\BrandRightsSourceService;
use Doraemon\tools\Log;

class RenewPackageService
{

    /**
     * 创建续费套餐
     * @param $brandId
     * @param $packageId
     * @param $orderId
     * @param $effectTime
     * @param $effectEndTime
     * @return false|int
     */
    public static function createRenewPackage($brandId, $packageId, $orderId, $inStartTime, $inEndTime)
    {
        Log::info('创建续费套餐', [$brandId, $packageId, $orderId, $inStartTime, $inEndTime]);
        $effectTime = strtotime($inStartTime);
        $effectEndTime = strtotime($inEndTime);
        $effectEndTime = strtotime(date('Y-m-d 23:59:59', $effectEndTime));
        $package = BrandPackageService::getInfo($packageId);
        if (!$package) {
            Log::error('套餐不存在！', func_get_args());
            return false;
        }
        $packageRights = BrandPackageRightsConfigService::getOnePackageRightsConfigs($packageId);
        if (empty($packageRights)) {
            Log::error('套餐权益未配置！', func_get_args());
            return false;
        }
        $orderWhere['id'] = $orderId;
        $orderWhere['pay_status'] = mBrandOrder::PAY_STATUS_PAID;
        $orderInfo = mBrandOrder::get('*', $orderWhere);
        if (empty($orderInfo)) {
            Log::error('订单不存在或未支付！', func_get_args());
            return false;
        }
        $addData['brand_id'] = $brandId;
        $addData['package_id'] = $packageId;
        $addData['pack_type'] = $package['pack_type'];
        $addData['effect_status'] = BrandRenewPackage::STATUS_EFFECTIVE_NO;
        $addData['renew_time'] = $orderInfo['pay_time'];
        $addData['effect_time'] = $effectTime;
        $addData['order_id'] = $orderId;
        $addData['data_status'] = BrandRenewPackage::STATUS_NORMAL;
        $addData['create_time'] = $addData['update_time'] = date('Y-m-d H:i:s', time());

        $ret = BrandRenewPackage::action(function () use ($addData, $brandId, $packageId, $effectTime, $effectEndTime) {
            $result = BrandRenewPackage::dataInsert($addData);
            if (!$result) {
                return false;
            }
            $packageRenewId = (int)$result;
            $result = RenewPackageRightsService::createPackageRenewRights($brandId, $packageRenewId, $packageId,
                $effectTime, $effectEndTime);
            if (!$result) {
                return false;
            }
            return true;
        });
        if (!$ret) {
            return false;
        }
        return true;
    }

    /**
     * 根据Id获取未生效的品牌续费套餐
     * @param $id 主键
     * @return mixed
     */
    public static function unEffectiveRenewPackage($id)
    {
        $where['id'] = $id;
        $where['data_status'] = BrandRenewPackage::STATUS_NORMAL;
        $where['effect_status'] = BrandRenewPackage::STATUS_EFFECTIVE_NO;
        return BrandRenewPackage::dataSelectInfo($where);
    }

    /**
     * 根据Id获取品牌续费套餐
     * @param $id 主键
     * @return mixed
     */
    public static function getBrandRenewPackage($id)
    {
        $where['id'] = $id;
        $where['data_status'] = BrandRenewPackage::STATUS_NORMAL;
        return BrandRenewPackage::dataSelectInfo($where);
    }

    /**
     * 获取全部未生效的品牌续费套餐
     * @return array|bool
     */
    public static function allUnEffectiveRenewPackage()
    {
        $where['data_status'] = BrandRenewPackage::STATUS_NORMAL;
        $where['effect_status'] = BrandRenewPackage::STATUS_EFFECTIVE_NO;
        return BrandRenewPackage::dataSelect($where);
    }


    /**
     * 分割处理未生效的品牌续费套餐
     * @param callable $callback
     * @return bool
     */
    public static function chunkUnEffectiveRenewPackage(callable $callback)
    {
        $where['data_status'] = BrandRenewPackage::STATUS_NORMAL;
        $where['effect_status'] = BrandRenewPackage::STATUS_EFFECTIVE_NO;
        $where['ORDER'] = [
            'id' => 'ASC'
        ];
        return BrandRenewPackage::dataChunk($where, 100, $callback);
    }

    /**
     * 定时生效续费套餐
     * @return bool
     */
    public static function crondEffectPackage()
    {
        $result = self::chunkUnEffectiveRenewPackage(function ($renewPackages) {
            foreach ($renewPackages as $renewPackage) {
                if ($renewPackage['effect_status'] == BrandRenewPackage::STATUS_EFFECTIVE_NO && $renewPackage['effect_time'] <= time()) {
                    self::effectRenewPackage($renewPackage['id']);
                }
            }
            return true;
        });
        return $result;
    }

    /**
     * 品牌续费套餐生效
     * @param $brandId
     * @return bool
     */
    public static function effectBrandRenewPackage($brandId)
    {
        $where['brand_id'] = $brandId;
        $where['effect_status'] = BrandRenewPackage::STATUS_EFFECTIVE_NO;
        $where['data_status'] = BrandRenewPackage::STATUS_NORMAL;
        $brandRenewPackage = BrandRenewPackage::dataSelectInfo($where);
        if (empty($brandRenewPackage)) {
            return false;
        }
        $bResult = self::effectRenewPackage($brandRenewPackage['id']);
        if (!$bResult) {
            return false;
        }

        #品牌账户信息
        $accountInfo = BrandAccountInfo::getOneByWhere([
            'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
            'brand_id' => $brandId,
            'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED
        ], ['id', 'in_start_time', 'in_end_time']);

        if ($accountInfo) {
            //恢复品牌等级保留权益
            $startTime = strtotime($accountInfo['in_start_time']);
            $endTime = strtotime($accountInfo['in_end_time']);
            $endTime = strtotime(date('Y-m-d 23:59:59', $endTime));
            $bResult = BrandLevelRightsService::levelRightsRecovery($brandId, $startTime, $endTime);
            if (!$bResult) {
                return false;
            }
        }
        return true;

    }


    /**
     * 续费套餐生效
     * @param $id 主键
     * @return bool
     */
    public static function effectRenewPackage($id)
    {
        $renewPackage = self::getBrandRenewPackage($id);

        if (empty($renewPackage)) {
            return false;
        }

        if ($renewPackage['effect_status'] == BrandRenewPackage::STATUS_EFFECTIVE_YES) {
            return true;
        }

        $orderInfo = BrandOrder::get('*', ['id' => $renewPackage['order_id']]);

        if (empty($orderInfo) || $orderInfo['pay_status'] != BrandOrder::PAY_STATUS_PAID) {
            return false;
        }

        $dsn = $orderInfo['dsn'];

        $result = BrandRenewPackage::action(function () use ($renewPackage, $dsn) {
            $result = RenewPackageRightsService::effectPackageRights($renewPackage['brand_id'], $renewPackage['id'],
                $dsn);
            if (!$result) {
                return false;
            }
            $data = [
                'effect_status' => BrandRenewPackage::STATUS_EFFECTIVE_YES,
                'update_time' => date('Y-m-d H:i:s', time()),
            ];
            $where['id'] = $renewPackage['id'];
            $result = BrandRenewPackage::dataUpdate($data, $where);
            if (!$result) {
                return false;
            }
            return true;

        });

        if ($result) {
            return true;
        }
        return false;
    }


}